import MySQLdb
import MySQLdb.cursors
import sys

import time

reload(sys)
sys.setdefaultencoding( "utf-8" )

class DB(object):
    def __init__(self, host, user, password, port, db):
        self.__host = host
        self.__user = user
        self.__password = password
        self.__port = port
        self.__db = db
        self.getConnect()


    def getConnect(self):
        try:
            self.__cn = MySQLdb.connect(host=self.__host, user=self.__user, passwd=self.__password, port=self.__port,cursorclass = MySQLdb.cursors.DictCursor,charset="utf8")
            self.__cn.select_db(self.__db)
            self.__cur = self.__cn.cursor()
            return True
        except MySQLdb.Error, e:
            # print "init error %d: %s" % (e.args[0], e.args[1])
            return False
    def usedb(self, db):
        self.ping()
        try:
            self.__db = db
            self.__cn.select_db(db)
            self.__cur = self.__cn.cursor()
        except MySQLdb.Error, e:
            print "usedb error %d: %s" % (e.args[0], e.args[1])

    def query(self, sql):
        self.ping()
        if (self.__cur == None):
            print "No connection or cursor!"
        else:
            count = self.__cur.execute(sql)
            return count, self.__cur.fetchall()

    def queryOne(self, sql):
        self.ping()
        if (self.__cur == None):
            print "No connection or cursor!"
        else:
            count = self.__cur.execute(sql)
            return self.__cur.fetchone()


    def execute(self, sql):
        self.ping()
        self.__cur = self.__cn.cursor()
        count = self.__cur.execute(sql)
        self.__cn.commit()
        return count
    #def close(self):
    def ping(self):
        stime = 2
        num = 28800
        _number = 0
        _status = True
        while _status and _number <= num:
            try:
                self.__cn.ping()
                _status = False
            except:
                try:
                    self.__cn.ping(True)
                    _status = False
                except Exception, e:
                    # print(str(e))
                    if self.getConnect() == True:
                        _status = False
                        break
                    _number +=1
                    time.sleep(stime)

class Data:
    db = None

def getDB():
    if Data.db==None:
        Data.db=DB("172.16.104.21", "root", "liuhua2017", 3306, "liuhua")
    Data.db.ping()
    return Data.db
    #return DB("127.0.0.1", "root", "123456", 3306, "liuhua")
    # import tools.DB_Driver as DB
    # db = DB.getDB()